Maximum Gap

Given an unsorted array, find the maximum difference between the successive elements in its sorted form.

Try to solve it in linear time/space.

Return 0 if the array contains less than 2 elements.

You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.

Solution:

  1. public class Solution {
  2. public int maximumGap(int[] nums) {
  3. if (nums == null || nums.length < 2) {
  4. return 0;
  5. }
  6. int n = nums.length;
  7. // m is the maximal number in nums
  8. int m = nums[0];
  9. for (int i = 1; i < n; i++) {
  10. m = Math.max(m, nums[i]);
  11. }
  12. int exp = 1; // 1, 10, 100, 1000 ...
  13. int R = 10; // 10 digits
  14. int[] aux = new int[n];
  15. while (m / exp > 0) { // Go through all digits from LSB to MSB
  16. int[] count = new int[R];
  17. for (int i = 0; i < n; i++) {
  18. count[(nums[i] / exp) % 10]++;
  19. }
  20. for (int i = 1; i < R; i++) {
  21. count[i] += count[i - 1];
  22. }
  23. for (int i = n - 1; i >= 0; i--) {
  24. aux[--count[(nums[i] / exp) % 10]] = nums[i];
  25. }
  26. for (int i = 0; i < n; i++) {
  27. nums[i] = aux[i];
  28. }
  29. exp *= 10;
  30. }
  31. int max = 0;
  32. for (int i = 1; i < aux.length; i++) {
  33. max = Math.max(max, aux[i] - aux[i - 1]);
  34. }
  35. return max;
  36. }
  37. }